﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

namespace Nirvana
{
    [CustomPropertyDrawer(typeof(ListStringVariate))]
    public class ListStringVariatePropertyDrawer : PropertyDrawer
    {
        private Dictionary<string, ReorderableList> listmap = new Dictionary<string, ReorderableList>();
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);
            SerializedProperty overwrite = property.FindPropertyRelative("overwrite");
            SerializedProperty value = property.FindPropertyRelative("value");
            ReorderableList reorderableList = this.InitList(property, overwrite, value);
            reorderableList.DoList(position);
            EditorGUI.EndProperty();
        }

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            SerializedProperty hasValue = property.FindPropertyRelative("hasValue");
            SerializedProperty value = property.FindPropertyRelative("value");
            ReorderableList reorderableList = this.InitList(property, hasValue, value);
            return reorderableList.GetHeight() + EditorGUIUtility.singleLineHeight;
        }

        private ReorderableList InitList(SerializedProperty property, SerializedProperty overwrite, SerializedProperty value)
        {
            ReorderableList reorderableList;
            if (listmap.TryGetValue(value.propertyPath, out reorderableList))
            {
                return reorderableList;
            }
            reorderableList = new ReorderableList(value.serializedObject, value);

            reorderableList.drawHeaderCallback = (rect) =>
            {
                overwrite.boolValue = EditorGUI.ToggleLeft(rect, property.displayName, overwrite.boolValue);
            };
            reorderableList.elementHeight = EditorGUIUtility.singleLineHeight;
            reorderableList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
            {
                GUI.enabled = overwrite.boolValue;
                SerializedProperty arrayElementAtIndex = value.GetArrayElementAtIndex(index);
                EditorGUI.PropertyField(rect, arrayElementAtIndex, GUIContent.none);
            };
            reorderableList.drawFooterCallback = (Rect rect) => {
                GUI.enabled = overwrite.boolValue;
                ReorderableList.defaultBehaviours.DrawFooter(rect, reorderableList);
                GUI.enabled = true;
            };

            this.listmap.Add(value.propertyPath, reorderableList);
            return reorderableList;
        }



    }
}

